package com.blockmeta.bbs.baselibrary.widget.custom

import android.animation.ObjectAnimator
import android.animation.ValueAnimator.REVERSE
import android.content.Context
import android.graphics.*
import android.os.Looper
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateInterpolator

/**
 * @author AirThor
 * @date 2018/6/4.
 * 行情涨跌闪动
 */
class FlashView : View {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    /**
     * 画笔颜色
     */
    private var paintColorRed = Color.parseColor("#51EE3F37")
    private var paintColorGreen = Color.parseColor("#5129B32A")
    /**
     * 涨跌颜色渐变
     */
    private lateinit var greenGradient: LinearGradient
    private lateinit var redGradient: LinearGradient
    /**
     * 是否绘制的标识位
     */
    private var canDraw = false
    /**
     * 动画
     */
    val alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f)
    /**
     * 行情是否上涨，同时启动动画
     */
    var isRise = false
        set(value) {
            field = value
            canDraw = true
            if (alphaAnimator.isRunning) alphaAnimator.cancel()
            if(Thread.currentThread()== Looper.getMainLooper().thread) {
                alphaAnimator.start()
            }
        }

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    init {
//        mAnimator.setRepeatMode(ValueAnimator.REVERSE);
//        mAnimator.setRepeatCount(ValueAnimator.INFINITE);
//        mAnimator.setInterpolator(new AccelerateInterpolator());
//        mAnimator.setDuration(1000);
//        mAnimator.start();
        alphaAnimator.repeatMode = REVERSE
        alphaAnimator.repeatCount =1
        alphaAnimator.interpolator = AccelerateInterpolator()

        alphaAnimator.duration = 1000
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        redGradient = LinearGradient(0f, 0f, measuredWidth.toFloat(), 0f, 0, paintColorRed, Shader.TileMode.REPEAT)
        greenGradient = LinearGradient(0f, 0f, measuredWidth.toFloat(), 0f, 0, paintColorGreen, Shader.TileMode.REPEAT)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (!canDraw) {
            return
        }
        paint.shader = if (isRise) greenGradient else redGradient
        if(!alphaAnimator.isRunning){
            paint.alpha=0
        }
        canvas.drawRect(0f, 0f, measuredWidth.toFloat(), measuredHeight.toFloat(), paint)
    }

    fun cancelAnimator(){
        if(alphaAnimator.isRunning){
            alphaAnimator.cancel()
        }
    }
}